/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 *
 * $Id: AudioClient.cpp,v 1.4 2009-12-01 09:32:21 morsko Exp $
 *
 * \file
 * \brief Implementation for Audio interface client library.
 * \author Matthieu Myrsky <matthieu.myrsky@tkk.fi>
 */

#include "AudioClient.hpp"
#include "AudioData.hpp"

//*****************************************************************************
using namespace MaCI::Audio;
//*****************************************************************************
//*****************************************************************************
#define GIMI_CLIENT_API (20000)
#include "gimi.h"
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
   
CAudioClient::CAudioClient(gimi::GIMI *aGIMIPtr, const int aInterfaceMinor)
 : CSync(1,1),
   CThread(1),
   CMaCI(aGIMIPtr, GIMI_PROTOCOL_MACI_AUDIO, aInterfaceMinor),
   iAudioSequence(0),
   iLastAudioData(),
   iAudioClientCallback(NULL),
   iAudioInfo()
{
 dPrint(4,"CAudioClient %p constructed", this);
 dPrint(1,"gimi ptr %p, is connected %d", aGIMIPtr,aGIMIPtr->isConnected());

}
//*****************************************************************************


CAudioClient::~CAudioClient()
{
  DoClose();
  dPrint(4,"CAudioClient %p destructed", this);
}
//*****************************************************************************

bool CAudioClient::GetAudioData(CAudioData &aAudioData, 
                                unsigned int *aAudioSeq,
                                const unsigned int aTimeout_ms)
{

  bool result = false;
  
  Lock();

  
  if (aAudioSeq == NULL) {
    // No sequence number defined. Just do direct copy of local data - no sync
    aAudioData = iLastAudioData;
    result = true;
   } else {
    dPrint(1,"GetAudioData(): iAudioSequence = %u, *aAudioSeq = %u", 
           iAudioSequence, *aAudioSeq);
    
    if (iAudioSequence <= *aAudioSeq) {
      int time_left = aTimeout_ms;
      unsigned int time_begin = ownTime_get_ms();
      
      // The available scan is older than requested - must wait for time_left
      do {
	Wait(time_left, KEventNewAudio);
	time_left = aTimeout_ms - ownTime_get_ms_since(time_begin);
	
      } while(IsActive() && iAudioSequence < *aAudioSeq && time_left > 0);
      
      // Now, check whether the waiting resulted in the correct sequence
      if (iAudioSequence > *aAudioSeq) {
	// Yes :)
        aAudioData = iLastAudioData;
	*aAudioSeq = iAudioSequence;
	result = true;
	
      } else {
	// No :(
	dPrint(1, "Failed to get AudioData! (Timeout %dms)",
	       aTimeout_ms);
      }
      
    } else {
     
      // The available scan is newer or matching age than requested.
      aAudioData = iLastAudioData;
      *aAudioSeq = iAudioSequence;
      result = true;
    }
  }
  
  Unlock();
  dPrint(10,"returning %d",result);
  return result;
    



}
//*****************************************************************************

bool CAudioClient::GetAudioInfo(TAudioInfo &aAudioInfo)
{
  if(IsActive()){
    aAudioInfo = iAudioInfo;
    return true;
  }else{
    dPrint(3,"Audio Client is closed. Please open it before getting audio info!");
    return false;
  }

}
//*****************************************************************************

bool CAudioClient::GetAudioInfoFromServer(const unsigned int aTimeout_ms)
{
  bool result = true;
  if(IsActive()){

    CAudioData ad;
    CAudioData reply;
    ad.CreateInternalBinBag();
    reply.CreateInternalBinBag();
    SMessageSource ms; 
    // Get unique MessageID.
    const unsigned int  queryID = GetUniqueMessageID();
    // Construct Data element with Command.
    result &=ad.SetCommand(TCommand(KCommandGetAudioInfo));
    if(result){
      dPrint(1,"Sending message with id %u",queryID);
      result = (SendInterfaceMessage(ad,queryID)==KMaCIOK);
      if(result){
        EMaCIError e =ReceiveSynchronousMessageReply(reply, ms,queryID, aTimeout_ms);
    
        if(e == KMaCIOK){
          if(reply.GetCommand()->cmd == KCommandGetAudioInfoReply){
            const TAudioInfo *audInfo = reply.GetAudioInfo();
            if(audInfo){
              iAudioInfo = *audInfo;

            }else{
              dPrint(3,"No audio info in reply message");
              result = false;
            }
            
          }else{
            dPrint(1,"Wrong command : '%d'. (should be '%d')",reply.GetCommand()->cmd,KCommandGetAudioInfoReply);
            result = false;
          }

        }else{
          dPrint(1,"No response within timeout time (error= %d)",e);
          result = false;
        }

      }
    } else {
      dPrint(ODERROR,"Failed to construct AudioData container with given parameters! Nothing sent.");
      
    }
  }else{
    result = false;
  }
  return result;
}
//*****************************************************************************

MaCI::EMaCIError CAudioClient::DoOpen(void)
{

  EMaCIError result = KMaCIError;
  
  // Checks.
  if(!IsActive()) {

    // Do Subs. using the MaCI provided function.
    result = SubscribeToInterface();

  

     
    // If all inits were fine...
    if (result == KMaCIOK) {
      // Start the Thread
      EnableSynchronousMessageReply();
      SetActive(true);


      //Then get audio info.
      if(!GetAudioInfoFromServer(TimeoutValue(2000))){
        dPrint(3,"Failed to get audio info from server");
        return KMaCIError;
      }

      CThread::RunThread();
      dPrint(4,"CAudioClient::DoOpen() was succesfull.");
      result = KMaCIOK;
    }

  } else {
    dPrint(4,"AudioClient already Active, not Opening again.");
    result = KMaCINotActive;

  }
  
  return result;
}
//*****************************************************************************


MaCI::EMaCIError CAudioClient::DoClose(void)
{
  EMaCIError result = KMaCIError;
  
  if(IsActive()) {
    SetActive(false);

    // Wait for thread to complete.
    /* CThread::CancelThread(); //Removed by script */
    CThread::WaitThread();
    result = UnsubscribeToInterface(TimeoutValue(2000));
  
    if(result == KMaCIOK){
      dPrint(4,"Succesfully closed AudioClient");    
    }else{
      dPrint(4,"Unsubscribing failed!");
    }
   
    
  } else {
    dPrint(4, "AudioClient not active, so not Closing.");
    result = KMaCINotActive;

  }
  
  return result;
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
int CAudioClient::ThreadFunction(const int aThreadNumber)
{
 int result = 0;
  const unsigned int hard_error_count_limit = 10;
  unsigned int hard_error_count = 0;
  EMaCIError e;
  gimi::GIMIMessage gmsg;
  
  assert(aThreadNumber == 0);
  assert(iGIMIPtr != NULL);
  
  dPrint(8, "GIMIMessage handler started");
  
  // Run as long as the thread should be active
  while(IsActive()) {
    // Call the ReceiveMessage wrapper with 1s timeout
    e = ReceiveInterfaceMessage(gmsg, 1000);
    if (e == KMaCIOK) {
      dPrint(1,"GOT MESSAGE seq %d",gmsg.messageId);
      ProcessMessage(gmsg);

      // Reset error counter.
      if (hard_error_count) hard_error_count = 0;

    } else if (e != KMaCITimeout) {
      // Increment hard error count
      ++hard_error_count;
      
      // Check whether the hard error count limit is still under limit. 
      if (hard_error_count < hard_error_count_limit) {
        // Other error, try to recover by sleeping one second.
        dPrint(10,"ProcessMessage returned error %u, trying to recover by sleeping 1000ms (%u attempts left)",
               e, hard_error_count_limit-hard_error_count);
        ownSleep_ms(1000);

      } else {
        dPrint(3,"Error Recovery failed, AudioClient ThreadFunction terminating...");

        // Break the while().
        break;
      }
      
    }
  }
  
  dPrint(8, "GIMIMessage handler stopped");
  SetActive(false);

  return result;

}
//*****************************************************************************
int CAudioClient::ProcessMessage(const gimi::GIMIMessage &msg)
{
  int result = 0;
  gim::binbag::CBinBag bb;
  CAudioData ad;
  bool r;
  
  r = bb.Decode(msg.getData(), msg.getDatalength());
  if (r) {
    // Succesfully decoded as BinBag.
    r = ad.DecodeFrom(&bb);
    if (r) {

      const TCommand *cmd = ad.GetCommand();
      if(cmd){
        switch(cmd->cmd){
        case KCommandNewAudio:{
          Lock();
          iLastAudioData = ad;
          ++iAudioSequence;
          Notify(KEventNewAudio);
          dPrint(1,"Got new audio, sequence now %u",iAudioSequence);
          Unlock();
          // Call the handler if set.
          if (iAudioClientCallback) {
            dPrint(8,"Got Callback for AudioDataEvent - executing!");
            iAudioClientCallback->OnAudioDataEvent(ad,
                                                   iAudioSequence,
                                                   *this);
            dPrint(8,"Callback for AudioDataEvent - execution complete!");
          }
          break;
        }

        case KCommandGetAudioInfoReply:{
          
          break;
        }
        default:
          dPrint(1,"Unidentified command! %d (%x)! Ignore.",
                 cmd->cmd, cmd->cmd);
          break;

        }
     
      }
    } else {
      dPrint(4,"WARNING: Received Audio interface message, but failed to decode as AudioData!");
      
    }
  }
  
  return result;

}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
   
